#!/usr/bin/env python3
# coding: utf-8

import zipfile as ZF  # slowpoke
import urllib.request as REQ
import os, sys, re
import shutil


if __name__ == "__main__":
    if not os.access('lvl_06_files', os.F_OK|os.X_OK):
        os.mkdir('lvl_06_files', 0o750)
    os.chdir('lvl_06_files')
    pants = REQ.urlopen('http://www.pythonchallenge.com/pc/def/channel.zip').readall()
    archive_file = open('channel.zip', mode='wb')
    archive_file.write(pants)
    archive_file.close()

    z = ZF.ZipFile('channel.zip')
    print(z.read('readme.txt').decode())
    nodes = z.namelist()

    node = re.findall(r'start from \d+', z.read('readme.txt').decode())
    node = re.findall(r'\d+', node[0])[0]
    acc_comments = b''

    for ctr in range(len(nodes) + 1):
        contents = z.read('{0}.txt'.format(node)).decode()
        print(contents)
        acc_comments += z.getinfo('{0}.txt'.format(node)).comment
        try:
            node = re.findall(r'nothing is \d+', contents)[0]
            node = re.findall(r'\d+', node)[0]
            print(node)
        except:
            print('looks like linked list ends here\n')
            break
        print()

    print(acc_comments.decode())

    os.unlink('channel.zip')
    os.chdir('..')
    os.rmdir('lvl_06_files')
